/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src.report.saving;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.query.JRJpaQueryExecuterFactory;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JasperViewer;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import src.domain.saving.Savtrx;

/**
 *
 * @author Yusup Jauhari Shandi <in.visi>
 */
@ManagedBean
@SessionScoped
public class RptTransaksiTabungan implements Serializable{
    private StreamedContent file;
    private EntityManager em;
    public RptTransaksiTabungan() {
    }
    
   
    
    public void showReport() {
        InputStream streamReport = null;
        ServletOutputStream servletOutputStream  = null;
        FacesContext ctx = null;
        try {
            ctx = FacesContext.getCurrentInstance();

        HttpServletResponse response = (HttpServletResponse) ctx
                .getExternalContext().getResponse();

        InputStream reportStream = ctx.getExternalContext()
                .getResourceAsStream("/saving/report/rptTransaksiTabungan.jasper");

        servletOutputStream = response.getOutputStream();
        

        
        response.setContentType("application/pdf");

        

        
        
            
            String path = ctx.getExternalContext().getRealPath("/saving/report/rptTransaksiTabungan.jasper") ;
            streamReport = JRLoader.getFileInputStream(path);
            List<Savtrx> list = new ArrayList();
            for (int i = 0; i < 100; i++) {
                    Savtrx savtrx = new Savtrx();
                    savtrx.getSaving().setAccountNo("100");
                    savtrx.getSaving().getCustomer().setCustomerName("chan");
                    savtrx.setTransDate(new Date());
                    savtrx.setTransferNo("tes");
                    savtrx.setAmount(new BigDecimal(10000000.0000));
                    
                    list.add(savtrx);
            }
            JRDataSource datasource = new JRBeanCollectionDataSource(list);
            Map<String, Object> map = new HashMap<> ();
            map.put(JRParameter.REPORT_DATA_SOURCE, datasource);
             map.put("p_periode", "Tahun 2012");
            //JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, map);
           // JasperExportManager.exportReportToPdfStream(reportStream, servletOutputStream);
            
            
            JasperPrint report = JasperFillManager.fillReport(streamReport,map);
            file = new DefaultStreamedContent(reportStream, "application/pdf", "rptTransaksiTabgunan.pdf");
            //JasperViewer.viewReport(report);
        } catch (Exception ex) {
            Logger.getLogger(RptTransaksiTabungan.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
             //   streamReport.close();
                servletOutputStream.flush();
                servletOutputStream.close();
                ctx.responseComplete();

            } catch (IOException ex) {
                Logger.getLogger(RptTransaksiTabungan.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public StreamedContent getFile() {
        return file;
    }
    
    //cara 2
    public void doPrint2(){
        ServletOutputStream servletOutputStream = null;
        FacesContext facesContext = FacesContext.getCurrentInstance();
        try {
            Map parameterMap = new HashMap();
            parameterMap.put(JRJpaQueryExecuterFactory.PARAMETER_JPA_ENTITY_MANAGER, em);
            parameterMap.put("p_periode", "Tahun 2012");
            
            HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
            InputStream reportStream = facesContext.getExternalContext().getResourceAsStream("/saving/report/rptTransaksiTabungan.jasper");
            servletOutputStream = response.getOutputStream();
            
            response.setContentType("applicaton/pdf");
            try {
                JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, parameterMap);
               // JasperExportManager.exportreporttop
            //    JasperExportManager.exportReportToPdfFile("build/web/saving/report/rptTransaksiTabungan.jrxml");
            } catch (JRException ex) {
                Logger.getLogger(RptTransaksiTabungan.class.getName()).log(Level.SEVERE, null, ex);
            }
            servletOutputStream.flush();
            servletOutputStream.close();
        } catch (IOException ex) {
            Logger.getLogger(RptTransaksiTabungan.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            facesContext.responseComplete();
            try {
                servletOutputStream.close();
            } catch (IOException ex) {
                Logger.getLogger(RptTransaksiTabungan.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
    }
    
    public void doPrint() {
        // Carrega o xml de definição do relatório
        try {
            FacesContext context = FacesContext.getCurrentInstance();
            HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
            ServletContext servletContext = (ServletContext) context.getExternalContext().getContext();
            // Configura o response para suportar o relatório
            response.setContentType("application/pdf");
            // response.addHeader("Content-disposition", "inline; filename=\"arquivo.pdf\"");
            response.addHeader("Content-disposition", "attachment; filename=\"rptTransaksiTabungan.pdf\"");
            String caminhoRelatorio = servletContext.getRealPath("/saving/report/rptTransaksiTabungan.jasper");
            HashMap<String, Object> parametroMap = new HashMap<>();
            parametroMap.put("p_periode", "Tahun 2012");
            // Preenche o relatório com os parametros e o data source
            JasperPrint jasperPrint = null;
            try {
                jasperPrint = JasperFillManager.fillReport(caminhoRelatorio, parametroMap,new JREmptyDataSource());
            } catch (JRException jRException) {
                System.out.println(jRException.toString());
            }
            // Exporta o relatório
            JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
            //new add
         //   JasperExportManager.exportReportToPdf(jasperPrint);
          //  JasperViewer.viewReport(jasperPrint);
            //end add
            // Salva o estado da aplicação no contexto do JSF
            context.getApplication().getStateManager().saveView(context);
            // Fecha o stream do response
            context.responseComplete();
        } catch (JRException | IOException e) {
          //  setExibeDialog(true);
          //  mensagem += e;
        }
    }
    
    
}
